package com.fumin.common;

import com.fumin.exception.ParamException;
import com.fumin.exception.PermissionExcetion;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author xiayuxuanmin
 * 异常处理类
 * @Date 2019/10/10
 * @Description
 */
//注意,这里要在spring里面配置SpringExceptionResolver,这样才能被spring管理,这样在发生异常的时候,才能通过这个class接受
//可以在spring-servlet.xml中配置<bean class="com.fumin.common.SpringExceptionResolver" />
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        String url = request.getRequestURI().toString();
        ModelAndView mv;
        String defaultMsg = "System error";//定义默认异常信息

        //.json,.page(为了方便知道前台需要后台返回什么格式的数据,这里约定整个项目中,如果url以.json结尾,那么需要返回给前台json数据,如果以.page结尾,则返回页面数据)
        if(url.endsWith(".json")){
            if(e instanceof PermissionExcetion || e instanceof ParamException){
                //如果抛出的是我们自定义的异常
                JsonData result = JsonData.fail(e.getMessage());
                mv = new ModelAndView("jsonView",result.toMap());//在spring-serlet.xml中配置了<bean id="jsonView">,两者是一致的
            }else{
                //系统异常
                JsonData result = JsonData.fail(defaultMsg);
                mv = new ModelAndView("jsonView",result.toMap());
                //把系统异常输出在日志里面
                log.error("unKnown json exception,url:"+url,e);
            }
        }else if (url.endsWith(".page")) {
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("exception",result.toMap());
            //把系统异常输出在日志里面
            log.error("unKnown page exception,url:"+url,e);
        }else{
            //其他请求,也直接返回一个json数据
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("jsonView",result.toMap());
            //把系统异常输出在日志里面
            log.error("unKnown other exception,url:"+url,e);
        }
        return mv;
    }
}
